<template>
    <div class="reactive">
        <h1>Reactive</h1>
        <form>
            <input v-model="form.name" type="text" />
            <br />
            <input v-model="form.age" type="text" />
            <button @click.prevent="submit">提交</button>
        </form>
        <hr />
        <ul>
            <span>方案一</span>
            <li v-for="item in list" :key="item">
                {{ item }}
            </li>
        </ul>
        <ul>
            <span>方案二</span>
            <li v-for="item in list" :key="item">
                {{ item }}
            </li>
        </ul>
        <button @click="add">添加</button>
        <hr />
        <div>{{ obj.name }}</div>
        <div>{{ read.name }}</div>

        <button @click="show">查看</button>
        <hr />
        <div>{{ obj2.foo.bar.num }}</div>
        <button @click="changeshallow">修改shallowReactive</button>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, readonly, shallowReactive } from 'vue'
// ref  reactive
// ref 支持所有类型  reactive 支持引用类型
// ref 取值 赋值都需要加.value reactive 是不需要.value
// reactive  由于是proxy代理  则不能直接赋值，否则会破坏响应式对象的
// 解决方案
//  1. push + 解构赋值
//  2. 添加一个对象吧数组作为一个属性去解决
type M = {
    name: string
    age: number
}

// form 表单
let form = reactive<M>({
    name: 'wangzy',
    age: 29
})
// 数组循环
let list = reactive<number[]>([])
// 数组循环
let list2 = reactive<{ arr: number[] }>({ arr: [] })
const submit = () => {
    console.log(form)
}
let timer: any
const add = () => {
    clearTimeout(timer)
    timer = setTimeout(() => {
        let res = [11, 223, 4343, 33]
        // list = res // reactive  由于是proxy代理  则不能直接赋值，否则会破坏响应式对象的
        list.push(...res) // 方案一
        list2.arr = res // 方案二
        timer = null
    }, 2000)
}

// readonly
let obj = reactive({ name: '只读' })
const read = readonly(obj)
const show = () => {
    obj.name = '不信'
    read.name = '不信' // readonly 会受原始定义影响
    console.log(obj, read)
}

// shallowReactive 与 shallowRef特性等都一样也是受 reactive 影响

const obj2 = shallowReactive({
    foo: {
        bar: {
            num: 1
        }
    }
})

const changeshallow = () => {
    obj2.foo.bar.num = 24 // 不生效
    obj2.foo = {
        bar: {
            num: 2222
        }
    }
}
</script>

<style scoped lang="less"></style>
